#ifndef KLINEWIDGET_H
#define KLINEWIDGET_H
#include "data_generate.h"
#include <QWidget>
#include <QApplication>
#include <QMainWindow>
#include <QWidget>
#include <QPainter>
#include <QVector>
#include <QPointF>
#include <QDateTime>
#include <QToolBar>
#include <QAction>
#include <QLabel>
#include <QSpinBox>
#include <QComboBox>
#include <QMouseEvent>
#include <QLinearGradient>
#include <cmath>
#include <algorithm>
#include <random>



class KLineWidget : public QWidget
{
    Q_OBJECT
public:


    explicit KLineWidget(QWidget *parent = nullptr);

    // 设置显示K线数量
    void setVisibleCount(int count);

    // 设置技术指标
    void setShowMA5(bool show) { showMA5 = show; update(); }
    void setShowMA10(bool show) { showMA10 = show; update(); }
    void setShowMA20(bool show) { showMA20 = show; update(); }
    void setShowVolume(bool show) { showVolume = show; update(); }
    void setShowVolumeMA5(bool show) { showVolumeMA5 = show; update(); }

protected:
    void paintEvent(QPaintEvent *event) override;

    void resizeEvent(QResizeEvent *event) override;

    void mouseMoveEvent(QMouseEvent *event) override;

    void leaveEvent(QEvent *event) override;

    void wheelEvent(QWheelEvent *event) override;

    void keyPressEvent(QKeyEvent *event) override;

signals:
    void visibleCountChanged(int count);

private:
    void calculatePriceRange();

    void calculateMA(int days);

    void calculateVolumeMA(int days);

    void drawBackground(QPainter &painter);

    void drawGrid(QPainter &painter);

    void drawKlines(QPainter &painter);

    void drawVolume(QPainter &painter);

    void drawMA(QPainter &painter, const QVector<double> &ma, QColor color);

    void drawCrosshair(QPainter &painter);

    void drawTitle(QPainter &painter);

    // 坐标转换函数
    int priceToY(double price);

    double yToPrice(int y);

    int indexToX(int index);

    int xToIndex(int x);

    // 计算图表区域
    void calculateChartArea();
private:
    // 成员变量
    QVector<KLineData> klineData;
    QVector<double> ma5;
    QVector<double> ma10;
    QVector<double> ma20;
    QVector<double> volumeMA5;

    int startIndex = 0;
    int visibleCount = 100;
    double minPrice = 0;
    double maxPrice = 0;
    double maxVolume = 0;

    bool showMA5 = true;
    bool showMA10 = true;
    bool showMA20 = true;
    bool showVolume = true;
    bool showVolumeMA5 = true;

    bool crosshairVisible = false;
    QPoint crosshairPos;

    int margin = 10;
    int chartTop = 0;
    int chartBottom = 0;
    int chartLeft = 0;
    int chartRight = 0;

};

#endif // KLINEWIDGET_H
